<?php
class PublicAction extends Action{
	//控制器初始化
	function _initialize(){

		
		//缓存时间，网站地址，基本信息，图片服务器地址
		if( F('cachetime') && F(md5('url')) && F(md5('info'))  && F(md5('img')) && F(md5('list')) ){
		    C('TMPL_PARSE_STRING.__ROOT__', F(md5('url')));
		    C('TMPL_PARSE_STRING.__IMGA__',F(md5('img')));
		    C('LIST', F(md5('list')));
		}else{
			$domain=null;$list=null;$img=null;$img1=null;
			$system=M('system');
			$res=$system->field('domain,list,img1,tel,qq,name,address,cachetime')->find(0);
		    $cachetime=$res['cachetime']*3600;   //缓存时间
		    $domain=$res['domain'];    		 //域名
		    $list=$res['list'];         			//网站所在目录

		    $info['tel']=$res['tel'];           		//联系电话
		    $info['qq']=$res['qq'];             		//QQ
		    $info['address']=$res['address'];   	//地址
		    $info['name']=$res['name'];         	//联系人

		            //获得本站网址
		    if(!empty($list)){
		        $url='http://'.$domain.'/'.trim($list,'/'); 
		    }else {
		        $url='http://'.$domain;
		    }
		           
		    C('LIST',trim($list,'/'));

		    C('TMPL_PARSE_STRING.__ROOT__',$url);

		    //图片服务器
		    if(!empty($res['img1'])){$img1=$res['img1'];}	
		    C('TMPL_PARSE_STRING.__PICSERVER1__',$img1);

		    F(md5('list'),trim($list,'/'));
		    F(md5('img'),$img);
		    F(md5('url'),$url);
		    F(md5('info'),$info);
		    F('cachetime',$cachetime);
		}
		//管理员权限控制
		if ('Admin'===GROUP_NAME) {
			if(!isset($_SESSION['admin']) || $_SESSION===null){
				$this->error('您没有访问权限！','/'.GROUP_NAME.'/Login',1);
			}
			if ($_SERVER['REMOTE_ADDR']!==$_SESSION['admin']['new_ip']) {
				$this->error('当前IP与登陆时不一致，请重新登陆！','/'.GROUP_NAME.'/Login');
			}
		}
		
		//RBAC权限控制
		if('Seoadmin'===GROUP_NAME){
		        	import('ORG.Util.Cookie');
			        // 用户权限检查
			        if (C('USER_AUTH_ON') && !in_array(MODULE_NAME, explode(',', C('NOT_AUTH_MODULE')))) {
				            import('ORG.Util.RBAC');
				            if (!RBAC::AccessDecision('admin')) {
					                //检查认证识别号
					                if (!$_SESSION [C('USER_AUTH_KEY')]) {
					                   	 //跳转到认证网关
					                   	 redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
					                }
				                	// 没有权限 抛出错误
				               	if (C('RBAC_ERROR_PAGE')) {
				                    	// 定义权限错误页面
				                   		redirect(C('RBAC_ERROR_PAGE'));
				            		} else {
				                    		if (C('GUEST_AUTH_ON')) {
				                    		$this->assign('jumpUrl', PHP_FILE . C('USER_AUTH_GATEWAY'));
				                    	}
				                    	// 提示错误信息
				                    	$this->error(L('_VALID_ACCESS_'));
				                }
			            }
		        	}			
		}

	}


	//空操作返回404页面
	public function _empty(){
		header("HTTP/1.0 404 Not Found");
		$this->display('./404.html');
	}

	/**
	 *U方法获得URL
	 *$result：内容结果集,三维数组
	 *$result[n]['contenturl']：路径	例1：news/  ；例2:new/id_
	 *$domain：二级域名
	 *$GroupHidden：隐藏分组名,默认false
	 *$result:返回带有内容URL的数组
	**/
	static protected function _url($result,$domain=Null,$GroupHidden=false){
 
            if(isset($result) && is_array($result)){
			for($i=0,$j=count($result);$i<$j;$i++){
                        			$menu=M('Menu');
                        			$where['typeid']=$result[$i]['typeid'];
                        			$urls=$menu->where($where)->field('contenturl')->find();
                        			$result[$i]['contenturl']=$urls['contenturl'];
			}
		}

				//组装非二级域名的路径
				if(is_array($result) && $domain==Null){
					$j=count($result);
					for($i=0;$i<$j;$i++){
						$result[$i]['url']=U($result[$i]['contenturl'].$result[$i]['id']);
						//隐藏分组名
						if($GroupHidden){
							$groupname=strtolower(GROUP_NAME);	//当前组名
							$result[$i]['url']=str_replace('/'.$groupname,'',$result[$i]['url']);
						}
					}
					return $result;
				}elseif(is_array($result) && $domain!=Null){
					//组装二级域名路径
					$j=count($result);
					for($i=0;$i<$j;$i++){
						$result[$i]['url']=U($result[$i]['contenturl'].$result[$i]['id'].'@'.$domain);
						//组藏分组名
						if($GroupHidden){
							$result[$i]['url']=PathConvert($result[$i]['url'],true);
						}
					}
					return $result;
				}else{
					return Null;
				}

	}

	//获得栏目URL
	static protected function getUrl($list,$li=false){

		if(isset($_GET['p']) && !empty($_GET['p'])){
			$p='_'.$_GET['p'];
		}else{
			$p='_1';
		}

		if(is_array($list)){
			foreach($list as $key=>$val){
				if(empty($val['url'])){
					if($val['typeid']){
						$list[$key]['url']='/'.$val['typeurl'].$val['typeid'].$p.'.'.C('URL_HTML_SUFFIX');
						$list[$key]['li']=$li;
					}
				}else{
					$list[$key]['url']=$list[$key]['url'].'" target="_blank';
					$list[$key]['li']=$li;
				}
			}
			return $list;	
		}

		if(is_numeric($list)){
			$where['typeid']=$list;
			$list=M('Menu')->where($where)->find();
			$list['url']='/'.$list['typeurl'].$list['typeid'].$p.'.'.C('URL_HTML_SUFFIX');
			return $list;
		}

		if($menus===null){
			$menus[$i]['url']=__ROOT__."/Index/page/id/".$_GET['id'];
		}

		return $menus;

	}


	//根据内容模型判断内容页URL
	protected function url($typeid){
		$menu=M('Menu');
		$res=$menu->where('typeid='.$typeid)->field('catid')->find();

		if($res['catid']==1){
			$url=__ROOT__.'/Article/show/id/';
		}elseif($res['catid']==2){
			$url=__ROOT__.'/Pic/show/id/';
		}elseif($res['catid']==3){
			$url=__ROOT__.'/Video/show/id/';
		}else{
			$this->error('参数错误');
		}

		return $url;
	}


	//查询所有子栏目,并返回栏目ID数组
	protected function types($typeid){
		$menu=M('Menu');
		$paths=$menu->field('typeid,path')->select();
		$j=count($paths);

		$n=0;	//统计子栏目数量
		for($i=0;$i<$j;$i++){
			if($paths[$i]['path']){
				$arr=explode(',',$paths[$i]['path']);
				if(in_array($typeid,$arr)){
					$typeids.=$paths[$i]['typeid'].',';
					$n++;
				}
			}
		}
		//如果子栏目数不为0则返回子栏目ID，否则返回空！
		if($n!=0){
			$typeids=rtrim($typeids,',');
			$typeids=explode(',',$typeids);
			return $typeids;	
		}else{
			return Null;
		}

	}

	//MYSQL查询
	//参数：表名，查询条件，返回字段，排序，是否分页
	//$table,$where,$fields,$order,$limit,$page=null
	protected function _select($table,$sql,$page=null,$pageurl){
		$sql['where']=isset($sql['where'])?$sql['where']:null;
		$sql['order']=isset($sql['order'])?$sql['order']:null;
		$sql['limit']=isset($sql['limit'])?$sql['limit']:null;
		$sql['field']=isset($sql['field'])?$sql['field']:null;

		$db=M(ucfirst($table));

		if($page!=null){
			//查询条件判断
			$x=$_GET['p']?$_GET['p']:0;
			$data=$db->where($sql['where'])->field($sql['field'])->order($sql['order'])->page($x,$page)->select();

			if(!$data){return;}

			import('ORG.Util.Page');					//导入分页类
			$count=$db->where($sql['where'])->count();	//获得符合条件的数据总数
			$Page=new Page($count,$page,'',$pageurl);		//实例化分页类 传入数据总数	
	
			//定义分页样式
			$Page->setConfig('prev','上页');
			$Page->setConfig('next','下页');
			$Page->setConfig('first','首页');
			$Page->setConfig('last','末页');
			$Page->rollPage = 20;
			$Page->setConfig('theme','%first% %upPage% %linkPage% %downPage% %end%');
				 
			$show= $Page->show();				//分页显示输出
			$data['page']=$show;				//将分页存入数据集


		}else{
			$data=$db->where($sql['where'])->field($sql['field'])->order($sql['order'])->limit($sql['limit'])->select();		
		}

		return $data;
	}

	//查询内容模型对应的表名	//参数:模型ID
	protected function tablename($id){
		$model=M('Model');
		$res=$model->field('tablename')->find($id);
		return $res['tablename'];
	}

	//缩略图地址
	protected function litimg($path){

		//拆分缩略图路径
		if(!empty($path)){
			$paths=explode('/',$path);
			if($paths[0]=='cj'){

				//如果是转换过来的图片则直接返回图片
				return $path;
			}else{
				//如果非采集图片则在图片名前加s_
				$paths=array_reverse($paths);
				$paths[0]='m_'.$paths[0];
				$paths=array_reverse($paths);
				return 'thumb/'.implode('/',$paths);
			}
		}else{
			return null;
		}
	}

	//获得栏目名称
	static protected function typename($typeid){

		//单栏目取出
		if(is_numeric($typeid)){
			$menu=M('menu');
			$type=$menu->where('typeid='.$typeid)->field('name')->find();
			return $type['name'];
		}

		//如果是字符串则转为数组
		if(is_string($typeid)){
			$typeid=explode(',',$typeid);
		}

		if(is_array($typeid)){
			$key=md5('typenames'.$typeid);
			$cache=S($key);
			if(!empty($cache)){
				$type=$cache;
			}else{
				$menu=M('menu');
				$type=$menu->field('typeid,name,typeurl')->select();
				S($key,$type,F('cachetime'));		
			}

			foreach($type as $k=>$v){
				foreach($typeid as $key){
					if($v['typeid']==$key){
						$type['id']=$v['typeid'];
						$type['name']=$key;
					}
				}
			}

			return $type;
		}

	}

	//批量获得栏目ID和名称，返回数组
	protected function typenames($typeids){
		$menu=M('Menu');
		for($i=0,$j=count($typeids);$i<$j;$i++){
			$type[$i]['typeid']=$typeids[$i];
			$name=$menu->where(array('typeid'=>$typeids[$i]))->field('name')->find();
			$type[$i]['name']=$name['name'];
		}
		return $type;
	}


	//页面公用头部
	protected function header(){
		//系统设置
		$sys=F('system');
		if($sys){$res=F('system');
		}else{
			$system=M('System');$res=$system->find();F('system',$res);		
		}

		if(ACTION_NAME=='index'){
			//输出首页标题
			$this->assign('seotitle',$res['seotitle']);
			$this->assign('keywords',$res['keywords']);
			$this->assign('description',$res['description']);
			$this->assign('public',true);
			$this->assign('index',true);
		}		

		$headhtml=stripcslashes($res['headhtml']);
		$foothtml=stripcslashes($res['foothtml']);

		$this->assign('sitename',$res['sitename']);
		$this->assign('beian',$res['beian']);
		$this->assign('headhtml',$headhtml);
		$this->assign('foothtml',$foothtml);

		if(ACTION_NAME=='page'){
			$this->assign('public',true);
			$this->assign('type',true);
		}

		if(ACTION_NAME=='show'){
			//echo '内容页';
			$this->assign('public',true);
			$this->assign('page',true);	
		}

	}
	
	protected function footer(){
		return null;
	}


	//过滤内容HTML标签
	static protected function getHtmlContent($list){
		$j=count($list);
		for($i=0;$i<$j;$i++){
			$list[$i]['content']=stripslashes($list[$i]['content']);
		}
		return $list;

	}




}
